package com.example.wuyeguanli.activity;

import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.IdlingRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.example.wuyeguanli.R;
import com.example.wuyeguanli.tools.ApiClient;
import com.example.wuyeguanli.tools.EspressoIdlingResource;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;

import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.replaceText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;

@RunWith(AndroidJUnit4.class)
public class FeeQueryActivityTest {

    private static MockWebServer mockWebServer;
    private static String originalBaseUrl;

    @BeforeClass
    public static void setUpClass() throws IOException {
        originalBaseUrl = ApiClient.BASE_URL;
        mockWebServer = new MockWebServer();
        mockWebServer.start(8080);
        ApiClient.setBaseUrlForTesting(mockWebServer.url("/").toString());
    }

    @AfterClass
    public static void tearDownClass() throws IOException {
        if (mockWebServer != null) {
            mockWebServer.shutdown();
        }
        ApiClient.setBaseUrlForTesting(originalBaseUrl);
    }

    @Before
    public void setUp() {
        IdlingRegistry.getInstance().register(EspressoIdlingResource.getIdlingResource());
    }

    @After
    public void tearDown() {
        IdlingRegistry.getInstance().unregister(EspressoIdlingResource.getIdlingResource());
    }

    @Test
    public void testQueryFee_Success() {
        // 1. 准备一个成功的Mock响应
        String successJson = "{\"state\":\"success\",\"error\":\"\",\"data\":{\"roomNumber\":\"101-101\",\"ownerPhone\":\"13800000000\",\"waterBalance\":123.45,\"electricityBalance\":67.89,\"propertyFeeBalance\":200.0}}";
        mockWebServer.enqueue(new MockResponse().setBody(successJson));

        ActivityScenario.launch(FeeQueryActivity.class);

        // 2. 模拟用户操作
        onView(withId(R.id.edit_room)).perform(replaceText("101101"), closeSoftKeyboard());
        onView(withId(R.id.btn_submit)).perform(click());

        // 3. 断言：验证TextView是否显示了正确的数据
        // Espresso会自动等待网络请求完成（因为有IdlingResource）
        onView(withId(R.id.water_num)).check(matches(withText("123.45")));
        onView(withId(R.id.elect_num)).check(matches(withText("67.89")));
        onView(withId(R.id.management_num)).check(matches(withText("200.0")));
    }

    @Test
    public void testQueryFee_RoomNotFound() {
        // 1. 准备一个房间不存在的错误响应
        String errorJson = "{\"state\":\"error\",\"error\":\"房间不存在，查询失败！\",\"data\":null}";
        mockWebServer.enqueue(new MockResponse().setBody(errorJson));

        ActivityScenario.launch(FeeQueryActivity.class);

        // 2. 模拟用户操作
        onView(withId(R.id.edit_room)).perform(replaceText("999999"), closeSoftKeyboard());
        onView(withId(R.id.btn_submit)).perform(click());

        // 3. 断言：验证TextView是否被清空
        onView(withId(R.id.water_num)).check(matches(withText("")));
        onView(withId(R.id.elect_num)).check(matches(withText("")));
        onView(withId(R.id.management_num)).check(matches(withText("")));
        // 对Toast的验证比较复杂，这里省略，但在手动测试中应能看到错误提示
    }
}